<?php
require_once("common.php");
$cz = $_GET['cz'];
$bookname = $_GET['book'] ?? 0;
function delthenovel($dirPath){
    $dirPath = $_SERVER['DOCUMENT_ROOT'].'/'.$dirPath;
    if (!is_dir($dirPath)) {
        die('参数错误'.$dirPath);
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }
    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            delthenovel($file);
        } else {
            unlink($file);
        }
    }
    rmdir($dirPath);
}
function delthebook($conn,$bookname){
    $sql = "select zj from novel where name='".$bookname."'";
if($conn -> query($sql)){
    if($row =$conn ->query($sql) -> fetch_assoc()){
        $zj = $row['zj'];
        delthenovel($zj);
        $sql = "DELETE FROM novel WHERE name='".$bookname."'";
        if($conn -> query($sql)){
            echo json_encode(array("code"=>200,"msg"=>"删除成功"));
        }else{
            echo json_encode(array("code"=>400,"msg"=>"删除失败"));
        }
    }
        }
$conn -> close();
}
function newfiles($directoryPath){
if(!is_dir($directoryPath)) {
    mkdir($directoryPath, 0777, true); 
}
}
function addbook($conn){
$name = $_GET['name'];
$content = $_GET['content'];
$url = $_GET['url'];
$user = $_GET['user'];
$linkfiles = 'novel/'.$name;
newfiles($_SERVER['DOCUMENT_ROOT'].'/'.$linkfiles);
$sql = "INSERT INTO novel (name,img,content,zj,refuse,fromer) VALUES ('".$name."','".$url."','".$content."','".$linkfiles."','0','".$user."')";
if($conn -> query($sql)){
    echo json_encode(array("code"=>200,"msg"=>"添加成功"));
}else{
    echo json_encode(array("code"=>400,"msg"=>"添加失败"));
}
}
if($cz == 'del'){
    delthebook($conn,$bookname);
}else if($cz == 'add'){
    addbook($conn);
}